package com.free.explayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import android.widget.SeekBar;

import com.free.explayer.permission.PermissionManager;
import com.free.explayer.player.OnPlayPositionChangeListener;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private MusicPlayerBinder mPlayerBinder;
    private Button mPlay;
    private SeekBar mSb;
    private boolean isStarted;
    private Intent mMusicServiceIntent;
    private boolean isStartedAndBinded;
    private boolean isBinded;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMusicServiceIntent = new Intent(this, MusicPlayerService.class);

        initViews();

        if (!PermissionManager.isGrantedReadExternalStoragePermission(this)) {
            PermissionManager.requestReadExternalStoragePermission(this);
        }
    }

    private void initViews() {
        mPlay = findViewById(R.id.play);
        mPlay.setOnClickListener(v -> {
            if (isPlaying()) {
                pause();
            } else {
                play();
            }
            updatePlayButton();
        });
        mSb = findViewById(R.id.sb);
        mSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // Mlog.i(TAG, "onProgressChanged, progress:%s, fromUser:%s", progress, fromUser);
                if (fromUser && mPlayerBinder != null && mPlayerBinder.isPlaying()) {
                    mPlayerBinder.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void updatePlayButton() {
        if (mPlayerBinder != null) {
            mPlay.setText(mPlayerBinder.isPlaying() ? "pause" : "play");
        }
    }

    private void play() {
        if (mPlayerBinder != null && !mPlayerBinder.isPlaying()) {
            mPlayerBinder.play();
        }
    }

    private void pause() {
        if (mPlayerBinder != null && mPlayerBinder.isPlaying()) {
            mPlayerBinder.pause();
        }
    }

    private boolean isPlaying() {
        if (mPlayerBinder != null) {
            return mPlayerBinder.isPlaying();
        }
        return false;
    }

    @Override
    protected void onStart() {
        super.onStart();
        isStarted = true;
        Mlog.i(TAG, "onStart");
        if (PermissionManager.isGrantedReadExternalStoragePermission(this)) {
            startAndBindMusicService();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Mlog.i(TAG, "onStop");
        isStarted = false;
        unBindMusicPlayerService();
    }

    private void startAndBindMusicService() {
        Mlog.i(TAG, "startAndBindMusicService");
        if (isStarted && !isStartedAndBinded) {
            isStartedAndBinded = true;
            startMusicPlayerService();
            bindMusicPlayerService();
        } else {
            Mlog.i(TAG, "startAndBindMusicService, do nothing.");
        }
    }

    private void startMusicPlayerService() {
        startService(mMusicServiceIntent);
    }

    private void bindMusicPlayerService() {
        Mlog.i(TAG, "bindMusicPlayerService, isBinded:%s", isBinded);
        if (!isBinded) {
            isBinded = true;
            bindService(mMusicServiceIntent, conn, BIND_AUTO_CREATE);
        }
    }

    private void unBindMusicPlayerService() {
        Mlog.i(TAG, "unBindMusicPlayerService, isBinded:%s", isBinded);
        if (isBinded) {
            isBinded = false;
            unbindService(conn);
        }
    }

    private final ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Mlog.i(TAG, "onServiceConnected");
            if (service instanceof MusicPlayerBinder) {
                mPlayerBinder = (MusicPlayerBinder) service;
                initAndPreparePlayer();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mPlayerBinder = null;
        }
    };

    private void initAndPreparePlayer () {
        if (mPlayerBinder != null) {
            Mlog.i(TAG, "initAndPreparePlayer, isPlaying:" + mPlayerBinder.isPlaying());
            if (!mPlayerBinder.isPlaying()) {
                mPlayerBinder.init();
                mPlayerBinder.preparePlay();
            }

            updatePlayButton();
            Mlog.i(TAG, "initAndPreparePlayer, duration:" + mPlayerBinder.getDuration());
            mSb.setMax(mPlayerBinder.getDuration());
            mPlayerBinder.setOnPlayPositionChangeListener(new OnPlayPositionChangeListener() {
                @Override
                public void onChange(int progress, int total) {
                    mSb.setProgress(progress);
                }
            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionManager.REQUEST_READ_EXTERNAL_STORAGE_CODE &&
                PermissionManager.onRequestReadExternalStoragePermission(requestCode, permissions, grantResults)) {
            startAndBindMusicService();
        }
    }
}